using System;
using System.Collections.Generic;
using System.Text;

using System.Data;
using System.Data.SqlClient;

namespace DataAccessLayer
{
    public class ReviewerGateway
    {
        private SqlConnection connection;

        private SqlCommand command;
        private SqlDataAdapter adapter;
        private SqlCommandBuilder builder;

        public ReviewerGateway(SqlConnection connection)
        {
            this.connection = connection;

            command = new SqlCommand("SELECT * FROM Reviewer WHERE id = @id", connection);
            command.Parameters.Add("@id", SqlDbType.BigInt);
            adapter = new SqlDataAdapter(command);
            builder = new SqlCommandBuilder(adapter);

        }

        public long Insert(string reviewerName, RecordingDataSet recordingDataSet) {
            RecordingDataSet.ReviewerRow newRow = recordingDataSet.Reviewer.NewReviewerRow();
            newRow.id = IdGenerator.GetNextId(recordingDataSet.Reviewer.TableName, connection);
            newRow.name = reviewerName;
            recordingDataSet.Reviewer.AddReviewerRow(newRow);
            Update(recordingDataSet);
            return newRow.id;
        }

        public RecordingDataSet.ReviewerRow FindById(long id, RecordingDataSet recordingDataSet)
        {
            command.Parameters["@id"].Value = id;
            adapter.Fill(recordingDataSet, recordingDataSet.Reviewer.TableName);

            DataRow[] rows = recordingDataSet.Reviewer.Select(String.Format("id={0}", id));

            if (rows.Length < 1) return null;

            return (RecordingDataSet.ReviewerRow) rows[0];
        }

        public void Delete(long deletedId, RecordingDataSet recordingDataSet)
        {
            RecordingDataSet.ReviewerRow row = FindById(deletedId, recordingDataSet);
            row.Delete();
            Update(recordingDataSet);
        }

        public void Update(RecordingDataSet recordingDataSet)
        {
            adapter.Update(recordingDataSet, recordingDataSet.Reviewer.TableName);
        }

    }
}
